import { create } from 'zustand';

// 保存搜索历史到本地存储的辅助函数
const saveSearchHistory = (history) => {
  localStorage.setItem('searchHistory', JSON.stringify(history));
};

const useSearchStore = create((set) => ({
  searchHistory: [],
  searchSuggestions: [],
  currentSearch: '',

  // 设置搜索历史
  setSearchHistory: (history) => {
    set({ searchHistory: history });
    // 保存到本地存储
    saveSearchHistory(history);
  },

  // 添加搜索记录
  addSearchRecord: (keyword) => {
    set((state) => {
      // 避免重复
      if (state.searchHistory.includes(keyword)) {
        return { ...state, currentSearch: keyword };
      }
      const newHistory = [keyword, ...state.searchHistory].slice(0, 10); // 最多保留10条
      saveSearchHistory(newHistory);
      return { searchHistory: newHistory, currentSearch: keyword };
    });
  },

  // 清除搜索历史
  clearSearchHistory: () => {
    set({ searchHistory: [] });
    localStorage.removeItem('searchHistory');
  },

  // 设置搜索建议
  setSearchSuggestions: (suggestions) => {
    set({ searchSuggestions: suggestions });
  },

  // 设置当前搜索关键词
  setCurrentSearch: (keyword) => {
    set({ currentSearch: keyword });
  },

  // 初始化搜索历史
  initSearchHistory: () => {
    try {
      const history = localStorage.getItem('searchHistory');
      if (history) {
        set({ searchHistory: JSON.parse(history) });
      }
    } catch (error) {
      console.error('Failed to load search history:', error);
    }
  }
}));

export default useSearchStore;